package com.ruoyi.bluebera.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.bluebera.domain.BizTxRecord;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.bluebera.domain.BizOrders;
import com.ruoyi.bluebera.service.IBizOrdersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户订单Controller
 * 
 * @author ruoyi
 * @date 2025-07-27
 */
@RestController
@RequestMapping("/bluebera/orders")
public class BizOrdersController extends BaseController
{
    @Autowired
    private IBizOrdersService bizOrdersService;

    /**
     * 查询用户订单列表--for admin
     */
    @PreAuthorize("@ss.hasPermi('bluebera:orders:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll(BizOrders bizOrders)
    {
        startPage();
        List<BizOrders> list = bizOrdersService.selectBizOrdersList(bizOrders);
        return getDataTable(list);
    }

    /**
     * 缩写交易哈希
     * @param txHash 原始交易哈希
     * @return 缩写后的哈希，如 abc123...fff999
     */
    public String abbreviateTxHash(String txHash)
    {
        if (txHash == null || txHash.length() <= 10) {
            return txHash;
        }
        // 前6位 + ... + 后4位
        String prefix = txHash.substring(0, 6);
        String suffix = txHash.substring(txHash.length() - 4);
        return prefix + "..." + suffix;
    }
    /**
     * 查询用户订单列表
     */
    //@PreAuthorize("@ss.hasPermi('bluebera:orders:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizOrders bizOrders)
    {
        startPage();
        String addr = bizOrders.getWalletAddress();
        if((null==addr) || (addr.trim().isEmpty())){
            return getDataTable(new ArrayList<>());
        }

        List<BizOrders> list = bizOrdersService.selectBizOrdersList(bizOrders);
        //  remove tx_status
        for(BizOrders order : list ){
            order.setNetwork("");
            order.setTxStatus("");
            // set order id
            order.setId(0L);
            order.setOrderId(abbreviateTxHash(order.getTxHash()));
        }
        return getDataTable(list);
    }

    /**
     * 导出用户订单列表
     */
    @PreAuthorize("@ss.hasPermi('bluebera:orders:export')")
    @Log(title = "用户订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizOrders bizOrders)
    {
        List<BizOrders> list = bizOrdersService.selectBizOrdersList(bizOrders);
        ExcelUtil<BizOrders> util = new ExcelUtil<BizOrders>(BizOrders.class);
        util.exportExcel(response, list, "用户订单数据");
    }

    /**
     * 获取用户订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('bluebera:orders:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizOrdersService.selectBizOrdersById(id));
    }


    public  String resolveNetwork(String tokenSymbol) {
        if (tokenSymbol == null) return null;

        switch (tokenSymbol.toUpperCase()) {
            case "ETH_USDT":
                return "1";
            case "ARB_USDT":
                return "42161";
            case "BERA":
                return "80094";
            default:
                return null; // 或抛出异常，如 throw new IllegalArgumentException("不支持的币种");
        }
    }

    /**
     * 新增用户订单
     */
    //@PreAuthorize("@ss.hasPermi('bluebera:orders:add')")
    @Log(title = "用户订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizOrders bizOrders)
    {
        // 1. 参数检查
        if (bizOrders == null || StringUtils.isEmpty(bizOrders.getWalletAddress())) {
            return AjaxResult.error("key parameter is null");
        }

        // 2. hash 判重
        String txHash = bizOrders.getTxHash();
        if (StringUtils.isNotEmpty(txHash)) {
            BizOrders order = new BizOrders();
            order.setTxHash(txHash);
            List<BizOrders> list = bizOrdersService.selectBizOrdersList(order);
            if ((list != null)&& list.size()>0 ){
                return AjaxResult.error("Transaction hash already exists, please do not submit again.");
            }
        }

        // 3. 状态设置
        if (StringUtils.isNotEmpty(txHash)) {
            bizOrders.setTxStatus("Processing");
            bizOrders.setStatus("Processing");
        } else {
            bizOrders.setTxStatus("Init");
            bizOrders.setStatus("Init");
        }

        // TODO: rate 校验 / network 解析可在这里加
        // String network = resolveNetwork(bizOrders.getTokenSymbol());
        // bizOrders.setNetwork(network);

        // 4. 插入记录
        return toAjax(bizOrdersService.insertBizOrders(bizOrders));
    }
    /*
    {
        // 1. check hash exist or not

        // 2. add record
        // init--processing--completed
        // check rate
        // set network according token symbol
        //String network = resolveNetwork(bizOrders.getTokenSymbol());
        //bizOrders.setNetwork(network);
        // set tx_status = processing by txhash
        String hash = bizOrders.getTxHash();
        if((null!=hash) && !(hash.trim().isEmpty())) {
            bizOrders.setTxStatus("Processing");
            bizOrders.setStatus("Processing");
        } else {
            bizOrders.setTxStatus("Init");
            bizOrders.setStatus("Init");
        }
        return toAjax(bizOrdersService.insertBizOrders(bizOrders));
    }

     */

    /**
     * 修改用户订单
     */
    //@PreAuthorize("@ss.hasPermi('bluebera:orders:edit')")
    @Log(title = "用户订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizOrders bizOrders)
    {
        return toAjax(bizOrdersService.updateBizOrders(bizOrders));
    }

    /**
     * 删除用户订单
     */
    @PreAuthorize("@ss.hasPermi('bluebera:orders:remove')")
    @Log(title = "用户订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bizOrdersService.deleteBizOrdersByIds(ids));
    }
}
